package com.cloudcc.mobile.view.main.fragment;

import android.app.AlertDialog;
import android.app.Dialog;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.net.Uri;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RadioButton;
import android.widget.RadioGroup;
import android.widget.TextView;
import android.widget.Toast;

import com.cloudcc.cloudframe.bus.EventEngine;
import com.cloudcc.cloudframe.bus.MenuToggleEvent;
import com.cloudcc.cloudframe.net.async.AsyncClient;
import com.cloudcc.cloudframe.util.PackageUtils;
import com.cloudcc.mobile.AppConfig;
import com.cloudcc.mobile.AppContext;
import com.cloudcc.mobile.AppManager;
import com.cloudcc.mobile.R;
import com.cloudcc.mobile.im.IMHelper;
import com.cloudcc.mobile.manager.CacheManager;
import com.cloudcc.mobile.manager.CloudCCPushManager;
import com.cloudcc.mobile.manager.ConfigManager;
import com.cloudcc.mobile.manager.ContactsManager;
import com.cloudcc.mobile.manager.RunTimeManager;
import com.cloudcc.mobile.manager.UrlManager;
import com.cloudcc.mobile.manager.UserManager;
import com.cloudcc.mobile.presenter.PushPresenter;
import com.cloudcc.mobile.service.DingWeiService;
import com.cloudcc.mobile.util.DialogUtils;
import com.cloudcc.mobile.view.activity.CloudccActivity;
import com.cloudcc.mobile.view.base.BaseFragment;
import com.cloudcc.mobile.view.main.MainUIActivity;
import com.cloudcc.mobile.view.main.SettingIMActivity;
import com.cloudcc.mobile.view.wel.GuideViewActivity;
import com.cloudcc.mobile.weight.DialogUtils.DialogOnClickListener;
import com.cloudcc.mobile.weight.SlideSwitch;
import com.cloudcc.mobile.weight.SlideSwitch.OnChangeListener;
import com.easemob.EMCallBack;
import com.lidroid.xutils.HttpUtils;
import com.lidroid.xutils.exception.HttpException;
import com.lidroid.xutils.http.RequestParams;
import com.lidroid.xutils.http.ResponseInfo;
import com.lidroid.xutils.http.callback.RequestCallBack;
import com.lidroid.xutils.http.client.HttpRequest.HttpMethod;
import com.litesuits.android.log.Log;
import com.pgyersdk.update.PgyUpdateManager;
import com.pgyersdk.update.UpdateManagerListener;
import com.pgyersdk.update.javabean.AppBean;

import butterknife.Bind;
import butterknife.OnClick;

/**
 * 设置界面
 * 
 * @author seven
 * 
 */
public class SettingFragment extends BaseFragment implements OnChangeListener {
	@Bind(R.id.setmessage)
	SlideSwitch togglePush;// 推送
	@Bind(R.id.setshengyin)
	SlideSwitch togglePushSound;// 推送声音
	@Bind(R.id.setzhengdong)
	SlideSwitch togglePushVibrate;// 推送震动
	@Bind(R.id.setloaction)
	SlideSwitch toggleLocal;// 位置
	@Bind(R.id.timeset)
	TextView timeset;
	@Bind(R.id.menu_setting)//全部按钮
	ImageView menu_setting;
	@Bind(R.id.menu_back_me)//返回按钮
	ImageView menu_back_me;
	@Bind(R.id.buttonLayout)//显示和隐藏
	LinearLayout buttonLayout;
	private LinearLayout update;
	 private String mEns = RunTimeManager.getInstance().getlanguage();
	 
	@Override
	public void init() {
		
		super.init();
		
		fillUI();
		addListener();
	}
	@Override
	public void onResume() {
		// TODO Auto-generated method stub
		super.onResume();
		setBack();
	}
	public void setBack(){
		final SharedPreferences sp = getActivity().getSharedPreferences("jump", 0);
		String mBack = sp.getString("mBacks", "isB");
		if ("backs".equals(mBack)) {
			menu_setting.setVisibility(View.GONE);
			menu_back_me.setVisibility(View.VISIBLE);
//			buttonLayout.setVisibility(View.GONE);
		}else{
			menu_setting.setVisibility(View.VISIBLE);
			menu_back_me.setVisibility(View.GONE);
			buttonLayout.setVisibility(View.VISIBLE);
		}
		menu_back_me.setOnClickListener(new OnClickListener() {
			
			@Override
			public void onClick(View v) {
				// TODO Auto-generated method stub
				sp.edit().clear();
				sp.edit().commit();
				((MainUIActivity) getActivity()).menu_foot.setVisibility(View.VISIBLE);
				((MainUIActivity) getActivity()).tabSelect(4);
			}
		});
		
	}
	//初始化页面
	private void fillUI() {
		 
		// #1 push
		togglePush.setSelected(ConfigManager.getInstance().isAllowPush());
		togglePushSound.setSelected(ConfigManager.getInstance()
				.isAllowPushSound());
		togglePushVibrate.setSelected(ConfigManager.getInstance()
				.isAllowPushVibrate());
		int time = 0;
		// location
		toggleLocal.setSelected(ConfigManager.getInstance().isAllowLocation());
		 int locationTime = ConfigManager.getInstance().getLocationTime();
		Log.d("settingfrag", "位置上报跟时间："+locationTime+"::"+ConfigManager.getInstance().isAllowLocation());
		HttpUtils utils = new HttpUtils();
		RequestParams params = new RequestParams();
		params.addBodyParameter("binding", RunTimeManager.getInstance()
				.getServerBinding());
		params.addBodyParameter("serviceName", "getSubmitPosInterval");
		utils.send(HttpMethod.POST, UrlManager.getInterfaceUrl(),params,
			new RequestCallBack<String>() {

				@Override
				public void onFailure(HttpException arg0, String arg1) {
					Log.d("-------------------------", "Failure。。。"
							+ arg1);
					Toast.makeText(mContext, "获取时间失败", 1).show();
				}

				@Override
				public void onSuccess(ResponseInfo<String> arg0) {
					String result = arg0.result;
					Log.d("-------------------------",
							"Success_down:     " + result);
					int time =(Integer.valueOf(result))*60*1000;
//					locationTime = time;
					Log.d("-------------------------",
							"Success_down:     " + time);
					switch (time) {
					case 3600000:
						timeset.setText(getResources().getString(R.string.yixiaoshi));
						break;
					case 7200000:
						timeset.setText(getResources().getString(R.string.lianggexiaoshi));
						break;
					case 3*60*60*1000:
						timeset.setText(getResources().getString(R.string.sanxiaoshi));
						break;
					case 5*60*1000:
						timeset.setText(getResources().getString(R.string.wufenzhong));
						break;
					case 10*60*1000:
						timeset.setText(getResources().getString(R.string.shifenzhong));
						break;
					case 30*60*1000:
						timeset.setText(getResources().getString(R.string.sanshifenzhong));
						break;
					}
				}
			});
		
	}
	
	@OnClick(R.id.guanyu)
	public void clickAboutMe() {
		Intent intent = new Intent(getActivity(), CloudccActivity.class);
		startActivity(intent);
		
	}

	@OnClick(R.id.weixin)
	public void clickSettingIM() {
		 Intent intent = new Intent(getActivity(), SettingIMActivity.class);
		 startActivity(intent);
	}

	@OnClick(R.id.huancun)
	public void clickClearCache() {
		DialogUtils.showClearCache(mContext);
	}
	@OnClick(R.id.shipinjiaoxue)
	public void clickShipin() {
		Uri uri = Uri.parse("http://study.cloudcc.com/weixin/home.html");
		Intent it = new Intent(Intent.ACTION_VIEW, uri);
		startActivity(it);
	}
	
	
	@OnClick(R.id.cloudcc_version)
	public void clickCheckViersion() {// 版本检测
		initNewVersion();
	}


	
	
	@OnClick(R.id.exit)
	public void clickExit() {
		DialogUtils.Exit(mContext);
	}

//	@OnClick(R.id.zhuxiao)
//	public void clickLoginOut() {
//		showClearLogin(mContext);
//	}

	@OnClick(R.id.menu_setting)
	public void menuTogggle() {
		EventEngine.post(new MenuToggleEvent(false, false));
	}

	@OnClick(R.id.xiaoxi)
	public void clickPushContainer() {
		togglePush.setSelected(togglePush.isSelected());
	}

	@OnClick(R.id.shengyin)
	public void clickPushSoundContainer() {
		togglePushSound.setSelected(togglePushSound.isSelected());
	}

	@OnClick(R.id.zhendong)
	public void clickPushVibrateContainer() {
		togglePushVibrate.setSelected(togglePushVibrate.isSelected());
	}

	@OnClick(R.id.weizhi)
	public void clickLoactionContainer() {
		Log.d("settingfrag", "位置上报的");
		toggleLocal.setSelected(toggleLocal.isSelected());
	}
//上报时间
	@OnClick(R.id.time)
	public void clickLoactionTimeContainer() {
		
		final AlertDialog dialog = new AlertDialog.Builder(mContext).create();
		final View view = LayoutInflater.from(mContext).inflate(
				R.layout.timesetting, null);
		
		final RadioButton rd1 = (RadioButton) view.findViewById(R.id.wufenzhong);
		final RadioButton rd2 = (RadioButton) view.findViewById(R.id.shifenzhong);
		final RadioButton rd3 = (RadioButton) view.findViewById(R.id.sanshifewnzhong);
		final String one = getActivity().getResources().getString(R.string.yixiaoshi);
		final String two = getActivity().getResources().getString(R.string.lianggexiaoshi);
		final String three = getActivity().getResources().getString(R.string.sanxiaoshi);
		final String wu = getActivity().getResources().getString(R.string.wufenzhong);
		final String shi = getActivity().getResources().getString(R.string.shifenzhong);
		final String sanshi = getActivity().getResources().getString(R.string.sanshifenzhong);
		if("Enterprise".equals(RunTimeManager.getInstance().getVersion())){
			rd1.setVisibility(View.GONE);
			rd2.setVisibility(View.GONE);
			rd3.setVisibility(View.GONE);
		}else if("Unlimited".equals(RunTimeManager.getInstance().getVersion())){
			rd1.setVisibility(View.VISIBLE);
			rd1.setVisibility(View.VISIBLE);
			rd1.setVisibility(View.VISIBLE);
		}
		dialog.setView(view);
		final RadioGroup radioGroup = (RadioGroup) view
				.findViewById(R.id.timesetting);
		String time = timeset.getText().toString().trim();
		Log.d("timeset", time+"timeset");
		if (time.equals(one)) {
			radioGroup.check(R.id.radio4);
		} else if (time.equals(two)) {
			radioGroup.check(R.id.radio5);
		} else if (time.equals(three)) {
			radioGroup.check(R.id.radio6);
		}else if (time.equals(wu)) {
			radioGroup.check(R.id.wufenzhong);
		}else if (time.equals(shi)) {
			radioGroup.check(R.id.shifenzhong);
		}else if (time.equals(sanshi)) {
			radioGroup.check(R.id.sanshifewnzhong);
		}
		final Button queren = (Button) view.findViewById(R.id.queren);
		final Button quxiao = (Button) view.findViewById(R.id.quxiao);
		quxiao.setOnClickListener(new OnClickListener() {
			@Override
			public void onClick(View v) {
				dialog.cancel();
			}
		});
		//点击dialog确定
		queren.setOnClickListener(new OnClickListener() {
			@Override
			public void onClick(View v) {
				RadioButton radioButton = (RadioButton) view
						.findViewById(radioGroup.getCheckedRadioButtonId());
				String timeText = radioButton.getText().toString().trim();
				timeset.setText(timeText);
				int times = AppConfig.LOCATION_TIME;
//				String one = getActivity().getResources().getString(R.string.yixiaoshi);
//				String two = getActivity().getResources().getString(R.string.lianggexiaoshi);
//				String three = getActivity().getResources().getString(R.string.sanxiaoshi);
//				String wu = getActivity().getResources().getString(R.string.wufenzhong);
//				String shi = getActivity().getResources().getString(R.string.shifenzhong);
//				String sanshi = getActivity().getResources().getString(R.string.sanshifenzhong);
				if (timeText.equals(one)) {
					times = 1*60*60*1000;
				} else if (timeText.equals(two)) {
					times = 2*60*60*1000;
				} else if (timeText.equals(three)) {
					times = 3*60*60*1000;
				}else if (timeText.equals(wu)) {
					times = 5*60*1000;
				}else if (timeText.equals(shi)) {
					times = 10*60*1000;
				}else if (timeText.equals(sanshi)) {
					times = 30*60*1000;
				}
				//存储到本地
				ConfigManager.getInstance().setLocationTime(times);
				//调用接口发送选择的时间上传
				Log.d("shezhishijian", "设置的时间："+times);
				HttpUtils utils = new HttpUtils();
				RequestParams params = new RequestParams();
				params.addBodyParameter("binding", RunTimeManager.getInstance()
						.getServerBinding());
				params.addBodyParameter("serviceName", "saveSubmitPosInterval");

				params.addBodyParameter("interval", times/1000/60+"");
				utils.send(HttpMethod.POST, UrlManager.getInterfaceUrl(),params,
					new RequestCallBack<String>() {
					String mEns = RunTimeManager.getInstance().getlanguage();
						@Override
						public void onFailure(HttpException arg0, String arg1) {
							Log.d("-------------------------", "Failure。。。"
									+ arg1);
							if ("en".equals(mEns)) {
								Toast.makeText(mContext, "Reporting time failed", 1).show();
							}else{
								Toast.makeText(mContext, "上报时间失败", 1).show();
							}
							
						}

						@Override
						public void onSuccess(ResponseInfo<String> arg0) {
							String result = arg0.result;
							Log.d("-------------------------",
									"Success_down:     " + result);
							if("true".equals(result)){
								if ("en".equals(mEns)) {
									Toast.makeText(mContext, "The reporting time is successful", 1).show();
								}else{
									Toast.makeText(mContext, "上报时间成功", 1).show();
								}
								
							}
						}
					});
				AppContext.locationtime = 10*60*1000;
				Intent intent = new Intent(getActivity(), DingWeiService.class);
				if (toggleLocal.isSelected()) {
					AppContext.isStopLocation = false;
					getActivity().stopService(intent);
					getActivity().startService(intent);
				}
				dialog.cancel();
			}
		});
		dialog.show();
	}

	/*
	 * 获取控件
	 */
	private void addListener() {
		togglePush.setOnChangeListener(this);// 消息监听
		togglePushSound.setOnChangeListener(this);// 声音监听
		togglePushVibrate.setOnChangeListener(this);// 震动监听
		toggleLocal.setOnChangeListener(this);
	}

	/**
	 * 注销登录
	 * 
	 * @param context
	 */
	public void showClearLogin(final Context context) {
		
		String zhuxiao ;
		if ("en".equals(mEns)) {
			zhuxiao = "Cancel account";
		}else{
			zhuxiao = "注销账户";
		}
		com.cloudcc.mobile.weight.DialogUtils.showWarn(mContext, zhuxiao, getResources().getString(R.string.tuichumiaoshu), new DialogOnClickListener() {
			@Override
			public void onClickPositive(final Dialog dialog) {
				//退出环信
				IMHelper.getInstance().logout(false, new EMCallBack() {
					
					@Override
					public void onSuccess() {
						getActivity().runOnUiThread(new Runnable() {
							public void run() {
								loginOut();
								
							}
						});
					}
					@Override
					public void onProgress(int arg0, String arg1) {
						
					}
					
					@Override
					public void onError(int arg0, String arg1) {
						dialog.cancel();
					}
				});

			}
			@Override
			public void onClickNegative(Dialog dialog) {
				dialog.cancel();
			}
		});
	}

	private void loginOut(){
		new PushPresenter().cancleBind();
		CacheManager.getInstance().clear();
		UserManager.getManager().clearUser();
		RunTimeManager.getInstance().clearUserCache();
		ContactsManager.getInstance().clearContactCache();
        UserManager.getManager().savezhuxiao(true);
		AsyncClient.getInstance().clear(mContext);
		Intent intent = new Intent(mContext,
				GuideViewActivity.class);
		intent.putExtra("page.index", 5);
		mContext.startActivity(intent);
		getActivity().finish();
		AppManager.getInstance().AppExit();
	}

	@Override
	public int getLayoutId() {
		return R.layout.setting2;
	}
	
	//SlideSwitch变化监听
	@Override
	public void onChange(SlideSwitch sb, boolean state) {
		Log.d("settingfrag", "位置上报的右边11"+state);
		ConfigManager configManager = ConfigManager.getInstance();
		switch (sb.getId()) {
		case R.id.setmessage:// push
			if (state) {
				CloudCCPushManager.getInstance().resumePushWork();
			} else {
				CloudCCPushManager.getInstance().stopPushWork();
			}
			configManager.setPush(state);
			break;
		case R.id.setshengyin:// push
			configManager.setAllowPushSound(state);
			break;
		case R.id.setzhengdong:// push
			configManager.setAllowPushVibrate(state);
			break;
		case R.id.setloaction:// locat
			Log.d("settingfrag", "位置上报的右边"+state);
			Intent intent = new Intent(getActivity(), DingWeiService.class);
			if (state) {
				AppContext.isStopLocation = false;
				getActivity().startService(intent);
			} else {
				AppContext.isStopLocation = true;
				getActivity().stopService(intent);
			}
			configManager.setlocation(state);
			break;

		default:
			break;
		}
	}

	private void initNewVersion(){
		new PgyUpdateManager.Builder()
				.setForced(false)                //设置是否强制更新,非自定义回调更新接口此方法有用
				.setUserCanRetry(false)         //失败后是否提示重新下载，非自定义下载 apk 回调此方法有用
				.setDeleteHistroyApk(false)     // 检查更新前是否删除本地历史 Apk
				.setUpdateManagerListener(new UpdateManagerListener() {
					@Override
					public void onNoUpdateAvailable() {
						//没有更新是回调此方法
						android.util.Log.d("pgyer", "there is no new version");
						if ("en".equals(mEns)) {
							Toast.makeText(getActivity(), "There is no latest version", Toast.LENGTH_LONG).show();
						}else{
							Toast.makeText(getActivity(), "没有最新版本", Toast.LENGTH_LONG).show();
						}

					}

					@Override
					public void onUpdateAvailable(AppBean appBean) {
						//更新是回调此方法
						android.util.Log.d("pgyer", "there is new version can update"
								+ "new versionCode is " + appBean.getVersionCode());
						if ("en".equals(mEns)) {
							showUpdateDialog(getActivity(), "check for updates", "jump to download the latest version?");
						} else {
							showUpdateDialog(getActivity(), "检查更新", "确认跳转去下载最新版本么？");
						}
					}


					@Override
					public void checkUpdateFailed(Exception e) {
						//更新检测失败回调
						android.util.Log.e("pgyer", "check update failed ", e);
						if ("en".equals(mEns)) {
							Toast.makeText(getActivity(), "There is no latest version", Toast.LENGTH_LONG).show();
						}else{
							Toast.makeText(getActivity(), "没有最新版本", Toast.LENGTH_LONG).show();
						}
					}
				}).register();
	}

	public void showUpdateDialog(final Context context, String title,
								 String message) {
		/**
		 * 自定义的dialog
		 */
		final AlertDialog builder = new AlertDialog.Builder(context).create();
		builder.setCancelable(false);
		View view = LayoutInflater.from(context)
				.inflate(R.layout.zhuxiao, null);
		builder.setView(view);
		builder.show();
		Button queren = (Button) view.findViewById(R.id.queren);
		Button quxiao = (Button) view.findViewById(R.id.quxiao);
		TextView titleName = (TextView) view.findViewById(R.id.titlename);
		TextView bodyName = (TextView) view.findViewById(R.id.bodyname);
		titleName.setText(title);
		bodyName.setText(message);
		queren.setOnClickListener(new OnClickListener() {
			@Override
			public void onClick(View v) {
				Uri uri = Uri.parse("https://www.pgyer.com/q3PD");
				Intent it = new Intent(Intent.ACTION_VIEW, uri);
				startActivity(it);
			}
		});
		quxiao.setOnClickListener(new OnClickListener() {
			@Override
			public void onClick(View v) {
				builder.cancel();
			}
		});
	}

}
